/**
 * @copyright 2017 sinping.com 北京芯平科技股份有限公司. All rights reserved.
 * 本内容仅限于北京芯平科技股份有限公司内部传阅，禁止外泄以及用于其他的商业目的.
 */
package com.sinping.qh.api.exception;

import com.sinping.qh.api.support.ConstEum;
import com.sinping.qh.api.support.ResDto;
import com.sinping.qh.utils.base.ExceptionUtil;
import com.sinping.qh.utils.mapper.JsonMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.InvocationTargetException;

/**
 * 蜗牛系统控制增强器
 *
 * @author xuerunjia
 * @create 2017/12/29
 */
@ControllerAdvice
public class CommonExceptionHandlerAdvice {

    private static final Logger log = LoggerFactory.getLogger(CommonExceptionHandlerAdvice.class);

    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseBody
    public String paramNullException(MissingServletRequestParameterException missException) {
        log.error("统一捕获请求参数缺失的异常:{}", ExceptionUtil.stackTraceText(missException));
        ResDto result = new ResDto(ConstEum.PARAM_ERROR);
        result.setMsg("param.error:" + missException.getParameterName());
        result.setDatas("{}");
        return JsonMapper.defaultMapper().toJson(result);
    }

    @ExceptionHandler(DataIntegrityViolationException.class)
    @ResponseBody
    public String paramDataIntegrException(DataIntegrityViolationException exception) {
        log.error("统一捕获数据库抛出的不符合定义的异常:{}", ExceptionUtil.stackTraceText(exception));
        ResDto result = new ResDto(ConstEum.PARAM_ERROR);
        result.setMsg("msg.param.error");
        result.setSub(exception.getMessage());
        result.setDatas("{}");
        return JsonMapper.defaultMapper().toJson(result);
    }


    /**
     * 自定义异常
     * @param handlerException
     * @return
     */
    @ExceptionHandler(HandlerException.class)
    @ResponseBody
    public String HandlerException(HandlerException handlerException) {
//        log.error("统一捕获异常:{}", ExceptionUtil.stackTraceText(handlerException));
        ResDto result = new ResDto(handlerException.getMStatus());
        result.setMsg(handlerException.getMessage());
        result.setDatas("{}");
        return JsonMapper.defaultMapper().toJson(result);
    }

    /**
     * 如果异常不在可控范围内,统一处理
     * @param exception
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String paramDataIntegrException(Exception exception) {
        log.error("统一捕获异常:{}", ExceptionUtil.stackTraceText(exception));
        ResDto result = new ResDto(ConstEum.SERVER_ERROR);
        result.setMsg(ConstEum.SERVER_ERROR.getMessage());
        result.setDatas("{}");
        return JsonMapper.defaultMapper().toJson(result);
    }
}
